#!/bin/bash
# 跨网络数据传输服务器 - 阿里云ECS部署脚本
# 支持数据持久化和跨网络环境

echo "=========================================="
echo "  跨网络数据传输服务器 ECS 部署脚本"
echo "=========================================="
echo

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 日志函数
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 错误处理
set -e
trap 'log_error "部署过程中发生错误，请检查上面的错误信息"' ERR

log_info "开始部署跨网络数据传输服务器到阿里云ECS..."

# 步骤1：更新系统
log_info "步骤1: 更新系统包..."
apt update && apt upgrade -y
log_success "系统更新完成"

# 步骤2：安装Python3和相关工具
log_info "步骤2: 安装Python3和相关工具..."
apt install -y python3 python3-pip python3-venv htop tree curl wget git
log_success "Python3和工具安装完成"

# 步骤3：创建项目目录
log_info "步骤3: 创建项目目录..."
mkdir -p /root/cross_network_server
cd /root/cross_network_server

# 确保server_data目录存在（用于数据持久化）
mkdir -p server_data
chmod 755 server_data

log_success "项目目录创建完成"

# 步骤4：安装Python依赖
log_info "步骤4: 安装Python依赖..."
pip3 install --upgrade pip

# 创建requirements.txt（如果不存在）
if [ ! -f "requirements.txt" ]; then
    cat > requirements.txt << 'EOF'
websockets==11.0.3
asyncio
logging
json
datetime
EOF
fi

pip3 install -r requirements.txt
log_success "Python依赖安装完成"

# 步骤5：创建systemd服务文件
log_info "步骤5: 配置systemd服务..."
cat > /etc/systemd/system/cross-network-server.service << 'EOF'
[Unit]
Description=Cross Network Data Transfer Server
After=network.target

[Service]
Type=simple
User=root
WorkingDirectory=/root/cross_network_server
ExecStart=/usr/bin/python3 /root/cross_network_server/cross_network_server.py
Restart=always
RestartSec=10
StandardOutput=journal
StandardError=journal

# 环境变量
Environment=PYTHONUNBUFFERED=1

[Install]
WantedBy=multi-user.target
EOF

# 重新加载systemd配置
systemctl daemon-reload
log_success "systemd服务配置完成"

# 步骤6：配置防火墙（如果安装了ufw）
log_info "步骤6: 配置防火墙规则..."
if command -v ufw &> /dev/null; then
    ufw allow 22/tcp comment 'SSH'
    ufw allow 8085/tcp comment 'Cross Network Server'
    ufw allow 80/tcp comment 'HTTP'
    ufw allow 443/tcp comment 'HTTPS'
    log_success "防火墙规则配置完成"
else
    log_warning "ufw未安装，跳过防火墙配置"
fi

# 步骤7：创建监控脚本
log_info "步骤7: 创建监控脚本..."
cat > /root/cross_network_server/monitor_server.sh << 'EOF'
#!/bin/bash
# 跨网络数据传输服务器监控脚本

LOG_FILE="/var/log/cross_network_server_monitor.log"
SERVICE_NAME="cross-network-server.service"

# 日志函数
log_message() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" >> $LOG_FILE
}

# 检查服务状态
check_service() {
    if ! systemctl is-active --quiet $SERVICE_NAME; then
        log_message "服务未运行，正在重启..."
        systemctl restart $SERVICE_NAME
        sleep 5
        
        if systemctl is-active --quiet $SERVICE_NAME; then
            log_message "服务重启成功"
        else
            log_message "服务重启失败"
        fi
    fi
}

# 检查端口监听
check_port() {
    if ! netstat -tlnp | grep ":8085" > /dev/null; then
        log_message "端口8085未监听，重启服务..."
        systemctl restart $SERVICE_NAME
    fi
}

# 检查磁盘空间
check_disk_space() {
    DISK_USAGE=$(df /root | tail -1 | awk '{print $5}' | sed 's/%//')
    if [ $DISK_USAGE -gt 90 ]; then
        log_message "警告: 磁盘使用率 ${DISK_USAGE}%"
    fi
}

# 主监控循环
log_message "监控脚本启动"
while true; do
    check_service
    check_port
    check_disk_space
    sleep 60  # 每分钟检查一次
done
EOF

chmod +x /root/cross_network_server/monitor_server.sh
log_success "监控脚本配置完成"

# 步骤8：创建数据备份脚本
log_info "步骤8: 创建数据备份脚本..."
cat > /root/cross_network_server/backup_data.sh << 'EOF'
#!/bin/bash
# 数据备份脚本

BACKUP_DIR="/root/backups"
DATE=$(date +%Y%m%d_%H%M%S)
DATA_DIR="/root/cross_network_server/server_data"

mkdir -p $BACKUP_DIR

if [ -d "$DATA_DIR" ]; then
    tar -czf "${BACKUP_DIR}/server_data_${DATE}.tar.gz" -C "/root/cross_network_server" server_data
    echo "$(date): 数据备份完成 - server_data_${DATE}.tar.gz"
    
    # 保留最近7天的备份
    find $BACKUP_DIR -name "server_data_*.tar.gz" -mtime +7 -delete
else
    echo "$(date): 数据目录不存在，跳过备份"
fi
EOF

chmod +x /root/cross_network_server/backup_data.sh
log_success "数据备份脚本配置完成"

# 步骤9：设置定时任务
log_info "步骤9: 配置定时任务..."
# 每天凌晨2点备份数据
(crontab -l 2>/dev/null; echo "0 2 * * * /root/cross_network_server/backup_data.sh >> /var/log/backup.log 2>&1") | crontab -
log_success "定时任务配置完成"

# 步骤10：启动服务
log_info "步骤10: 启动服务..."
systemctl enable cross-network-server.service

# 检查服务器文件是否存在
if [ -f "/root/cross_network_server/cross_network_server.py" ]; then
    systemctl start cross-network-server.service
    log_success "服务启动完成"
else
    log_warning "cross_network_server.py文件不存在，请手动上传后启动服务"
fi

# 步骤11：显示部署信息
log_info "步骤11: 显示部署信息..."
echo
echo "=========================================="
echo "         部署完成！"
echo "=========================================="
echo
echo "服务信息:"
echo "- 服务名称: cross-network-server.service"
echo "- 监听端口: 8085"
echo "- 数据目录: /root/cross_network_server/server_data"
echo "- 备份目录: /root/backups"
echo
echo "管理命令:"
echo "- 查看状态: systemctl status cross-network-server.service"
echo "- 查看日志: journalctl -u cross-network-server.service -f"
echo "- 重启服务: systemctl restart cross-network-server.service"
echo "- 停止服务: systemctl stop cross-network-server.service"
echo
echo "监控和维护:"
echo "- 启动监控: nohup /root/cross_network_server/monitor_server.sh > /dev/null 2>&1 &"
echo "- 手动备份: /root/cross_network_server/backup_data.sh"
echo "- 查看监控日志: tail -f /var/log/cross_network_server_monitor.log"
echo
echo "网络信息:"
echo "- 公网IP: $(curl -s ifconfig.me 2>/dev/null || echo '请检查网络连接')"
echo "- WebSocket地址: ws://$(curl -s ifconfig.me 2>/dev/null):8085"
echo
echo "下一步操作:"
echo "1. 确保上传了 cross_network_server.py 文件"
echo "2. 更新Android客户端配置"
echo "3. 重新编译APK"
echo "4. 测试连接"
echo
echo "=========================================="

log_success "部署脚本执行完成！"